<!DOCTYPE html>
<html>
<head>
    <title>在线上报</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
    <script src="style/common.js"></script>
    <script src="style/weui.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0&ak=qfh7gShdfdsxfh03Plv2yMunAd6wUQ7o&services=&t=20200327103013"></script>
<!--    <script src="style/img-compressor.js"></script>-->
    <link rel="stylesheet" href="style/weui.css"/>
</head>
<body>
<div class="page">
    <div class="weui-gallery" id="gallery">
        <span class="weui-gallery__img" id="galleryImg"></span>
        <div class="weui-gallery__opr" id="galleryImgDel" >
            <a href="#" class="weui-gallery__del">
                <i class="weui-icon-delete weui-icon_gallery-delete"></i>
            </a>
        </div>
    </div>
    <form id="form-add">
        <div class="weui-form">
            <div class="weui-form__text-area">
                <h2 class="weui-form__title">在线上报</h2>
            </div>
            <div class="weui-form__control-area">
                <div class="weui-cells__group weui-cells__group_form">
                    <div class="weui-cells " >
                        <div class="weui-cell">
                            <div class="weui-cell__hd"><label class="weui-label">手机号码</label></div>
                            <div class="weui-cell__bd">
                                <input class="weui-input" id="js_phone" type="number" name="phone" pattern="[0-9]*" placeholder="请输入手机号" />
                            </div>
                        </div>
                        <div class="weui-cell">
                            <div class="weui-cell__hd"><label class="weui-label">姓名</label></div>
                            <div class="weui-cell__bd">
                                <input class="weui-input" id="js_name" name="name" placeholder="请输入姓名" />
                            </div>
                        </div>
                        <div class="weui-cell">
                            <div class="weui-cell__hd"><label class="weui-label">地址</label></div>
                            <div class="weui-cell__bd">
                                <div id="l-map"style="display:none;"></div>
                                <input class="weui-input" id="js_address"  name="address" placeholder="请填写现场地址" />
                                <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                            </div>
                        </div>
                        <div class="weui-cell">
                            <div class="weui-cell__bd">
                                <div class="weui-uploader">
                                    <div class="weui-uploader__hd">
                                        <p class="weui-uploader__title">照片</p>
                                        <div class="weui-uploader__info" id="infoSFZ">0/1</div>
                                    </div>
                                    <div class="weui-uploader__bd">
                                        <ul class="weui-uploader__files" id="uploaderFilesSFZ">
                                        </ul>
                                        <div class="weui-uploader__input-box" id="updateSfz" >
                                            <input id="uploaderInputSFZ" name="imageSFZ" class="weui-uploader__input"
                                                   type="file" accept="image/*"  multiple/>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <br>
                <div class="button-sp-area" style="text-align: center;">
                    <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary" id="js_update">提交</a>
                </div>
                <div class="weui-footer">
                    <p class="weui-footer__text">Copyright © 2008-2019 湖南省第一测绘院</p>
                </div>
            </div>
        </div>
    </form>
    <br>
    <br>
    <br>
    <div id="js_toast" style="display:none;">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast">
            <i class="weui-loading weui-icon_toast"></i>
            <p class="weui-toast__content">数据上传中</p>
        </div>
    </div>
</div>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"/>
<!-- <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> -->
<script src="c"></script>
<script type="text/javascript">

    $(function () {
        var lng,lat;

        var geolocation = new BMap.Geolocation();
        var geoc = new BMap.Geocoder();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
               lng=r.point.lng;
               lat=r.point.lat;
            }
            else {
                alert('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true})
        // 百度地图API功能
        function G(id) {
            return document.getElementById(id);
        }

        var map = new BMap.Map("l-map");
        map.centerAndZoom("北京",12);                   // 初始化地图,设置城市和地图级别。

        var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
            {"input" : "js_address"
                ,"location" : map
            });


        var myValue;
        ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
            var _value = e.item.value;
            myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        });



        var $id = $('#js_id');
        var $phone = $('#js_phone');
        var $name = $('#js_name');
        var $sfz = $('#js_sfz');
        var $address = $('#js_address');
        var $toast = $('#js_toast');
        var imageSFZ;


        var $gallery = $("#gallery"), $galleryImg = $("#galleryImg"), $galleryImgDel = $("#galleryImgDel");
        var liDel;//记录删除元素
        //照片上传
        var tmplSFZ = '<li class="weui-uploader__file" name="fileSFZ" style="background-image:url(#url#)"></li>',
            $infoSFZ = $("#infoSFZ"),
            $uploaderInputSFZ = $("#uploaderInputSFZ"),
            $uploaderFilesSFZ = $("#uploaderFilesSFZ")
        ;
        $uploaderInputSFZ.on("change", function (e) {
            if (parseInt($infoSFZ.html().split('/')[0]) >= 1) return;
            var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
            for (var i = 0, len = files.length; i < 1; ++i) {
                var file = files[i];
                compressImg(file);
                if (url) {
                    src =  url.createObjectURL(file);
                } else {
                    src = e.target.result;
                }
                $uploaderFilesSFZ.append($(tmplSFZ.replace('#url#', src)));
                $infoSFZ.html((parseInt($infoSFZ.html().split('/')[0]) + 1) + "/1");


            }
        });
        $uploaderFilesSFZ.on("click", "li", function () {
            liDel = this;
            $galleryImg.attr("style", this.getAttribute("style"));
            $galleryImg.attr("imageId", this.getAttribute("imageId"));
            $gallery.fadeIn(100);
        });

        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });
        $galleryImgDel.on("click", function () {
            liDel.remove();
            if (liDel.getAttribute("name") == "fileSFZ") {
                $infoSFZ.html((parseInt($infoSFZ.html().split('/')[0]) - 1) + "/1");
            }

        });
        $('#js_update').on('click', function () {
                if ($(this).hasClass('weui-btn_disabled')) return;
                if ($phone.val() == "") {
                    weui.alert("请输入手机号码！");
                    return;
                }
                if ($name.val() == "") {
                    weui.alert("请输入姓名！");
                    return;
                }
                if ($address.val() == "") {
                    weui.alert("请输入地址！");
                    return;
                }

                //这里唯一需要注意的就是这个form-add的id
                var formData = new FormData($("#form-add")[0]);
                formData.append("lng",lng);
                formData.append("lat",lat);
                formData.append("file",imageSFZ);
                formData.delete("imageSFZ");
                $.ajax({
                    //接口地址
                    url: 'http://'+window.ip+':'+window.port+'/uploadreport',
                    type: 'POST',
                    data: formData,
                    cache: false,
                    async: true,
                    processData: false,  //必须false才会避开jQuery对 formdata 的默认处理
                    contentType: false,  //必须false才会自动加上正确的Content-Type
                    success: function (data) {
                        //成功的回调
                        if (data.code == 200) {
                            $toast.fadeOut(100);
                        }
                        var r = confirm("上报成功");
                        if (r == true) {
                            window.close();
                        } else {
                            window.close();
                        }

                    },
                    error: function (returndata) {
                        $toast.fadeOut(100);
                        //请求异常的回调
                        // modals.warn("网络访问失败，请稍后重试!");
                        weui.alert("单个上传文件不得超过4MB，总上传文件大小不得超过50MB！");
                    }
                });

                $toast.fadeIn(100);

        });

        //压缩图片
        function compressImg(file) {
            let reader = new FileReader();
            reader.readAsDataURL(file)
            reader.onload = function(e) {

                let image = new Image()  ;   //新建一个img标签（不嵌入DOM节点，仅做canvas操作)
                image.src = e.target.result  ;  //让该标签加载base64格式的原图
                image.onload = function() {    //图片加载完毕后再通过canvas压缩图片，否则图片还没加载完就压缩，结果图片是全黑的
                    var canvas = document.createElement('canvas'); //创建一个canvas元素
                    var context = canvas.getContext('2d');    //context相当于画笔，里面有各种可以进行绘图的API
                    //默认按照比例压缩
                    var scale=this.width/this.height;
                    var  canvasWidth;
                    var canvasHeight;
                    if(this.width<this.height){
                        //规定压缩后的大小
                        canvasWidth=1600;
                        canvasHeight=canvasWidth/scale;
                    }else{
                        canvasHeight=1600;
                        canvasWidth=canvasHeight*scale;
                    }
                    var data = '' ;   //存储压缩后的图片
                    canvas.width = canvasWidth ;  //设置绘图的宽度
                    canvas.height = canvasHeight  ;  //设置绘图的高度

                    //使用drawImage重新设置img标签中的图片大小，实现压缩。drawImage方法的参数可以自行查阅W3C
                    context.drawImage(image, 0, 0, canvasWidth, canvasHeight)

                    data = canvas.toDataURL('image/jpeg');


                    imageSFZ=dataURLtoFile(data,file.name);

                }
            }

        }


        function dataURLtoFile(dataurl, filename) {//将base64转换为文件
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, {type:mime});
        }

    });
</script>

</body>
</body>
</body>
</html>